package com.tcoiss.webservice.apiServer;

import com.alibaba.fastjson.JSON;
import com.tcoiss.common.core.utils.DateUtils;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.webservice.domain.invoice.RecordCommonVo;
import com.tcoiss.webservice.utils.AesUtils;
import com.tcoiss.webservice.utils.SignatureUtil;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class HttpInvoker extends Invoker{

    public Map<String,Object> invoke(HttpAPIServer httpAPIServer,InvokeContext invokeContext) throws Exception {
        Map<String,Object> resultMap = new HashMap<>();
        String targerUrl = invokeContext.getEndpoint();
        if(targerUrl.contains("$")){
            targerUrl = getEndpoint(invokeContext);
        }
        String response = "";
        String reqBody = generateRequestString(invokeContext);
        invokeContext.setRequestTime(DateUtils.getTime());

        //根据请求方式
        if(StringUtils.equals("post",invokeContext.getRequestType())&&StringUtils.equals("application/json",invokeContext.getDataType())){
            response = httpAPIServer.doPostJson(targerUrl,reqBody,invokeContext);
        }else if (StringUtils.equals("post",invokeContext.getRequestType())&&StringUtils.equals("parameters",invokeContext.getDataType())){
            targerUrl = targerUrl+reqBody;
            response = httpAPIServer.doPost(targerUrl);
        }else if (StringUtils.equals("get",invokeContext.getRequestType())&&StringUtils.equals("parameters",invokeContext.getDataType())){
            //拼装请求地址
            //String encode = URLEncoder.encode(reqBody, "UTF-8");
            targerUrl = targerUrl+reqBody;
            response = httpAPIServer.doGet(targerUrl,invokeContext);
        }else {
            //对请求参数进行转码
            //String encode = URLEncoder.encode(reqBody, "UTF-8");
            targerUrl = targerUrl+reqBody;
            response = httpAPIServer.doGet(targerUrl);
        }
        //response 不为null时，解析响应为Map
        if(!StringUtils.isEmpty(response)){
            resultMap = JSON.parseObject(response);
        }
        return resultMap;
    }

}
